package com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.util;

import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.constant.VoiceRecognitionConstant;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 讯飞API鉴权工具类
 */
public class AuthUtil {

    /**
     * 生成鉴权URL
     *
     * @return 带有鉴权参数的WebSocket URL
     * @throws Exception 鉴权过程中的异常
     */
    public static String generateAuthUrl() throws Exception {
        URI uri = new URI(VoiceRecognitionConstant.WEBSOCKET_URL);
        
        // 获取当前GMT时间，用于签名
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        
        // 拼接签名字符串
        String preStr = "host: " + uri.getHost() + "\n" +
                       "date: " + date + "\n" +
                       "GET " + uri.getPath() + " HTTP/1.1";
        
        // 使用HMAC-SHA256算法结合APISecret对签名原始字段签名
        Mac mac = Mac.getInstance("hmacSHA256");
        SecretKeySpec spec = new SecretKeySpec(
                VoiceRecognitionConstant.API_SECRET.getBytes(StandardCharsets.UTF_8), 
                "hmacSHA256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64编码获得最终的signature
        String signature = Base64.getEncoder().encodeToString(hexDigits);
        
        // 拼接authorization_origin字符串
        String authorizationOrigin = String.format(
                "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                VoiceRecognitionConstant.API_KEY, "hmac-sha256", "host date request-line", signature);
        
        // 对authorization_origin进行base64编码获得最终的authorization参数
        String authorization = Base64.getEncoder().encodeToString(authorizationOrigin.getBytes(StandardCharsets.UTF_8));
        
        // 将编码后的字符串url encode后添加到url后面
        return VoiceRecognitionConstant.WEBSOCKET_URL +
                "?authorization=" + URLEncoder.encode(authorization, "UTF-8") +
                "&date=" + URLEncoder.encode(date, "UTF-8") +
                "&host=" + uri.getHost();
    }
} 